package com.pitaya.winwine.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.pitaya.winwine.domain.Topic;
import com.pitaya.winwine.domain.User;
import com.pitaya.winwine.repository.TagRepository;
import com.pitaya.winwine.repository.TopicRepository;
import com.pitaya.winwine.service.TopicService;

@Controller
@RequestMapping("/talk")
public class TalkAction {
	
	@Autowired
	private TopicRepository topicRepository;

	@Autowired
	private TagRepository tagRepository;
	
	@Autowired
	private TopicService topicService;
	
	@RequestMapping
	public ModelAndView index(HttpSession session) {
		Map model = new HashMap();
	    model.put("hotTagList", tagRepository.findByTopicHotTagByLimit(6));
	    
	    Page page = topicRepository.findAll(new PageRequest(0, 30, new Sort(Sort.Direction.DESC, "editTime")));
	    model.put("page", page);
	    User user = (User)session.getAttribute("user");
	    if(user != null) {
	    	List<Topic> recommendList = topicRepository.findRecommedByLimit(user.getId(), 1);
	    	if(recommendList.size() == 1) {
	    		Topic recommend = recommendList.get(0);
	    		model.put("recommend", recommend);
	    	}
	    }
	    return new ModelAndView("topic/index", model);
	}
	
	@RequestMapping("/create")
	public ModelAndView create() {
		return new ModelAndView("topic/create", "tagList", tagRepository.findByOrderByTypeAscIdAsc());
	}
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(HttpSession session, @PathVariable("id") Integer id) {
	    Integer userId = ((User)session.getAttribute("user")).getId();
	    Map model = new HashMap();
	    Topic topic = topicRepository.findOne(id);
	    if (topic.getUser().getId() != userId) {
	      return new ModelAndView("redirect:/talk/detail/{id}", "id", id);
	    }
	    model.put("topic", topic);
	    model.put("tagList", tagRepository.findByTopicIdByStatus(id));
	    return new ModelAndView("topic/edit", model);
	}
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public ModelAndView save(HttpSession session, Topic topic) {
	    User user = (User)session.getAttribute("user");
	    topic.setUser(user);
	    topicService.save(topic);
	    return new ModelAndView("redirect:/talk");
	}
	
	
	@RequestMapping("/right")
	public ModelAndView right() {
		// TODO
		return new ModelAndView("topic/right");
	}
}
